<!--
  素材库组件
  显示和管理项目素材
-->
<template>
  <div class="asset-library">
    <!-- 头部 -->
    <div class="library-header">
      <n-text strong>素材库</n-text>
      <n-button-group size="small">
        <n-button quaternary @click="importAssets">
          <template #icon>
            <n-icon><AddOutline /></n-icon>
          </template>
          导入
        </n-button>
        <n-button quaternary @click="refreshAssets">
          <template #icon>
            <n-icon><RefreshOutline /></n-icon>
          </template>
        </n-button>
      </n-button-group>
    </div>
    
    <!-- 搜索栏 -->
    <div class="library-search">
      <n-input
        v-model:value="searchQuery"
        placeholder="搜索素材..."
        clearable
        size="small"
      >
        <template #prefix>
          <n-icon><SearchOutline /></n-icon>
        </template>
      </n-input>
    </div>
    
    <!-- 分类标签 -->
    <div class="library-tabs">
      <n-tabs 
        v-model:value="activeTab" 
        type="segment" 
        size="small"
        @update:value="handleTabChange"
      >
        <n-tab-pane name="all" tab="全部" />
        <n-tab-pane name="characters" tab="角色" />
        <n-tab-pane name="scenes" tab="场景" />
        <n-tab-pane name="props" tab="道具" />
        <n-tab-pane name="effects" tab="特效" />
        <n-tab-pane name="audio" tab="音频" />
      </n-tabs>
    </div>
    
    <!-- 素材列表 -->
    <div class="library-content">
      <n-scrollbar style="max-height: calc(100vh - 200px);" :x-scrollable="false">
        <div class="asset-grid">
          <div
            v-for="asset in filteredAssets"
            :key="asset.id"
            class="asset-item"
            :draggable="true"
            @dragstart="handleDragStart(asset, $event)"
            @click="selectAsset(asset)"
            :class="{ selected: selectedAsset?.id === asset.id }"
          >
            <!-- 缩略图 -->
            <div class="asset-thumbnail">
              <img 
                v-if="asset.thumbnail"
                :src="asset.thumbnail"
                :alt="asset.name"
                @error="handleImageError"
              />
              <div v-else class="thumbnail-placeholder">
                <n-icon size="24" :color="getAssetTypeColor(asset.type)">
                  <component :is="getAssetTypeIcon(asset.type)" />
                </n-icon>
              </div>
              
              <!-- 类型标识 -->
              <div class="asset-type-badge">
                <n-tag size="tiny" :type="getAssetTypeTagType(asset.type)">
                  {{ getAssetTypeLabel(asset.type) }}
                </n-tag>
              </div>
              
              <!-- 时长标识（音频/视频） -->
              <div 
                v-if="asset.duration" 
                class="asset-duration"
              >
                {{ formatDuration(asset.duration) }}
              </div>
            </div>
            
            <!-- 信息 -->
            <div class="asset-info">
              <n-text class="asset-name" :title="asset.name">
                {{ asset.name }}
              </n-text>
              <n-text depth="3" class="asset-size">
                {{ formatFileSize(asset.size) }}
              </n-text>
            </div>
            
            <!-- 操作按钮 -->
            <div class="asset-actions">
              <n-button-group size="tiny">
                <n-button quaternary @click.stop="previewAsset(asset)">
                  <template #icon>
                    <n-icon><EyeOutline /></n-icon>
                  </template>
                </n-button>
                <n-button quaternary @click.stop="editAsset(asset)">
                  <template #icon>
                    <n-icon><CreateOutline /></n-icon>
                  </template>
                </n-button>
                <n-button quaternary @click.stop="deleteAsset(asset)">
                  <template #icon>
                    <n-icon><TrashOutline /></n-icon>
                  </template>
                </n-button>
              </n-button-group>
            </div>
          </div>
        </div>
        
        <!-- 空状态 -->
        <div v-if="filteredAssets.length === 0" class="empty-state">
          <n-icon size="48" color="#ccc">
            <FolderOpenOutline />
          </n-icon>
          <p>{{ searchQuery ? '未找到匹配的素材' : '暂无素材' }}</p>
          <n-button @click="importAssets">
            导入素材
          </n-button>
        </div>
      </n-scrollbar>
    </div>
    
    <!-- 素材预览模态框 -->
    <n-modal v-model:show="showPreview" preset="card" style="width: 600px;">
      <template #header>
        素材预览 - {{ previewAssetData?.name }}
      </template>
      
      <div v-if="previewAssetData" class="asset-preview">
        <div class="preview-content">
          <img
            v-if="previewAssetData.type === 'image'"
            :src="previewAssetData.url || previewAssetData.thumbnail"
            :alt="previewAssetData.name"
            style="max-width: 100%; max-height: 400px;"
          />

          <video
            v-else-if="previewAssetData.type === 'video'"
            :src="previewAssetData.url"
            controls
            style="max-width: 100%; max-height: 400px;"
          />

          <audio
            v-else-if="previewAssetData.type === 'audio'"
            :src="previewAssetData.url"
            controls
            style="width: 100%;"
          />

          <div v-else class="preview-placeholder">
            <n-icon size="64" color="#ccc">
              <component :is="getAssetTypeIcon(previewAssetData.type)" />
            </n-icon>
            <p>{{ previewAssetData.name }}</p>
          </div>
        </div>
        
        <div class="preview-info">
          <n-descriptions :column="2" size="small">
            <n-descriptions-item label="类型">
              {{ getAssetTypeLabel(previewAssetData.type) }}
            </n-descriptions-item>
            <n-descriptions-item label="大小">
              {{ formatFileSize(previewAssetData.size) }}
            </n-descriptions-item>
            <n-descriptions-item v-if="previewAssetData.resolution" label="分辨率">
              {{ previewAssetData.resolution.width }}×{{ previewAssetData.resolution.height }}
            </n-descriptions-item>
            <n-descriptions-item v-if="previewAssetData.duration" label="时长">
              {{ formatDuration(previewAssetData.duration) }}
            </n-descriptions-item>
          </n-descriptions>
        </div>
      </div>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import {
  NText,
  NButton,
  NButtonGroup,
  NIcon,
  NInput,
  NTabs,
  NTabPane,
  NScrollbar,
  NTag,
  NModal,
  NDescriptions,
  NDescriptionsItem
} from 'naive-ui'
import {
  AddOutline,
  RefreshOutline,
  SearchOutline,
  EyeOutline,
  CreateOutline,
  TrashOutline,
  FolderOpenOutline,
  ImageOutline,
  VideocamOutline,
  VolumeHighOutline,
  SparklesOutline,
  CubeOutline,
  PersonOutline,
  ImagesOutline
} from '@vicons/ionicons5'
import { useEditorStore } from '../../stores/editor'
import type { AssetData, AssetType } from '../../services/types'
import { message } from '../../utils/message'

// 状态管理
const editorStore = useEditorStore()

// 本地状态
const searchQuery = ref('')
const activeTab = ref('all')
const selectedAsset = ref<AssetData | null>(null)
const showPreview = ref(false)
const previewAssetData = ref<AssetData | null>(null)

// 模拟素材数据
const mockAssets = ref<AssetData[]>([
  {
    id: '1',
    name: '主角小明',
    type: 'character',
    category: '角色',
    path: '/assets/characters/xiaoming.png',
    size: 1024000,
    thumbnail: '/assets/thumbnails/xiaoming.jpg',
    metadata: { format: 'png' },
    tags: ['主角', '男性'],
    createdAt: '2024-01-01',
    updatedAt: '2024-01-01',
    isPublic: false,
    downloadCount: 0,
    rating: 5,
    license: {
      type: 'free',
      name: 'Free License',
      commercial: true,
      modification: true,
      distribution: true
    }
  },
  {
    id: '2',
    name: '森林背景',
    type: 'scene',
    category: '场景',
    path: '/assets/scenes/forest.jpg',
    size: 2048000,
    resolution: { width: 1920, height: 1080 },
    thumbnail: '/assets/thumbnails/forest.jpg',
    metadata: { format: 'jpg' },
    tags: ['自然', '森林'],
    createdAt: '2024-01-01',
    updatedAt: '2024-01-01',
    isPublic: false,
    downloadCount: 0,
    rating: 4,
    license: {
      type: 'free',
      name: 'Free License',
      commercial: true,
      modification: true,
      distribution: true
    }
  }
])

// 计算属性
const filteredAssets = computed(() => {
  let assets = mockAssets.value
  
  // 按分类过滤
  if (activeTab.value !== 'all') {
    assets = assets.filter(asset => asset.type === activeTab.value)
  }
  
  // 按搜索关键词过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    assets = assets.filter(asset => 
      asset.name.toLowerCase().includes(query) ||
      asset.tags.some(tag => tag.toLowerCase().includes(query))
    )
  }
  
  return assets
})

// 方法
const handleTabChange = (value: string) => {
  activeTab.value = value
}

const handleDragStart = (asset: AssetData, event: DragEvent) => {
  if (event.dataTransfer) {
    event.dataTransfer.setData('application/json', JSON.stringify(asset))
    event.dataTransfer.effectAllowed = 'copy'
  }
}

const selectAsset = (asset: AssetData) => {
  selectedAsset.value = asset
}

const previewAsset = (asset: AssetData) => {
  previewAssetData.value = asset
  showPreview.value = true
}

const editAsset = (asset: AssetData) => {
  message.info('素材编辑功能开发中...')
}

const deleteAsset = (asset: AssetData) => {
  message.warning('确定要删除这个素材吗？')
}

const importAssets = () => {
  message.info('素材导入功能开发中...')
}

const refreshAssets = () => {
  message.success('素材库已刷新')
}

const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.style.display = 'none'
}

// 工具函数
const getAssetTypeIcon = (type: AssetType) => {
  const icons = {
    image: ImageOutline,
    video: VideocamOutline,
    audio: VolumeHighOutline,
    character: PersonOutline,
    scene: ImagesOutline,
    animation: SparklesOutline,
    model: CubeOutline,
    texture: ImageOutline,
    font: CreateOutline,
    document: FolderOpenOutline,
    archive: FolderOpenOutline,
    other: FolderOpenOutline
  }
  return icons[type] || FolderOpenOutline
}

const getAssetTypeColor = (type: AssetType): string => {
  const colors = {
    image: '#52c41a',
    video: '#1890ff',
    audio: '#722ed1',
    character: '#ff7875',
    scene: '#13c2c2',
    animation: '#fa8c16',
    model: '#eb2f96',
    texture: '#52c41a',
    font: '#faad14',
    document: '#8c8c8c',
    archive: '#8c8c8c',
    other: '#8c8c8c'
  }
  return colors[type] || '#8c8c8c'
}

const getAssetTypeLabel = (type: AssetType): string => {
  const labels = {
    image: '图片',
    video: '视频',
    audio: '音频',
    character: '角色',
    scene: '场景',
    animation: '动画',
    model: '模型',
    texture: '纹理',
    font: '字体',
    document: '文档',
    archive: '压缩包',
    other: '其他'
  }
  return labels[type] || '未知'
}

const getAssetTypeTagType = (type: AssetType): "default" | "error" | "success" | "warning" | "primary" | "info" => {
  const types: Record<AssetType, "default" | "error" | "success" | "warning" | "primary" | "info"> = {
    image: 'success',
    video: 'info',
    audio: 'warning',
    character: 'error',
    scene: 'info',
    animation: 'warning',
    model: 'error',
    texture: 'success',
    font: 'warning',
    document: 'default',
    archive: 'default',
    other: 'default'
  }
  return types[type] || 'default'
}

const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}

const formatDuration = (seconds: number): string => {
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${mins}:${secs.toString().padStart(2, '0')}`
}

// 生命周期
onMounted(() => {
  // 初始化素材库
})
</script>

<style lang="scss" scoped>
.asset-library {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: var(--card-color);
}

.library-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid var(--border-color);
}

.library-search {
  padding: 8px 16px;
  border-bottom: 1px solid var(--border-color);
}

.library-tabs {
  border-bottom: 1px solid var(--border-color);
  
  :deep(.n-tabs-nav) {
    padding: 0 16px;
  }
}

.library-content {
  flex: 1;
  overflow: hidden;
}

.asset-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 8px;
  padding: 16px;
}

.asset-item {
  position: relative;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.2s ease;
  background: var(--body-color);
  
  &:hover {
    border-color: var(--primary-color);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    
    .asset-actions {
      opacity: 1;
    }
  }
  
  &.selected {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 2px rgba(var(--primary-color-rgb), 0.2);
  }
  
  &:active {
    transform: scale(0.98);
  }
}

.asset-thumbnail {
  position: relative;
  width: 100%;
  height: 80px;
  overflow: hidden;
  background: #f5f5f5;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .thumbnail-placeholder {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    background: #fafafa;
  }
  
  .asset-type-badge {
    position: absolute;
    top: 4px;
    left: 4px;
  }
  
  .asset-duration {
    position: absolute;
    bottom: 4px;
    right: 4px;
    background: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 2px 4px;
    border-radius: 2px;
    font-size: 10px;
    font-family: monospace;
  }
}

.asset-info {
  padding: 8px;
  
  .asset-name {
    display: block;
    font-size: 12px;
    line-height: 1.2;
    margin-bottom: 2px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .asset-size {
    font-size: 10px;
  }
}

.asset-actions {
  position: absolute;
  top: 4px;
  right: 4px;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  text-align: center;
  color: #999;
  
  p {
    margin: 16px 0;
  }
}

.asset-preview {
  .preview-content {
    text-align: center;
    margin-bottom: 16px;
  }
  
  .preview-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 200px;
    color: #999;
    
    p {
      margin-top: 16px;
    }
  }
}
</style>
